﻿using System;
using TheOutLetLibrary.Dominio;
using System.Data.OleDb;

namespace TheOutLetLibrary.Infraestrutura {

    public class Accessk_orderDAO: BaseDAO, Ik_orderDAO {

        public Accessk_orderDAO(OleDbTransaction transacao)
            : base(transacao) {
        }

        public int Inclua(k_order order) {

            OleDbCommand comando = GetCommand();

            comando.CommandText = "INSERT INTO k_order (" +
                " NR_PEDIDO, DateCreated, LastUpdated, Status) " +
                " VALUES (" +
                " @NR_PEDIDO, @DateCreated, @LastUpdated, @Status)";

            comando.Parameters.Add("@NR_PEDIDO", OleDbType.Integer).Value = order.NR_PEDIDO;
            comando.Parameters.Add("@DateCreated", OleDbType.VarChar).Value = order.DateCreated.ToString("s");
            comando.Parameters.Add("@LastUpdated", OleDbType.VarChar).Value = order.LastUpdated.ToString("s");
            comando.Parameters.Add("@Status", OleDbType.VarChar).Value = order.Status;
            comando.ExecuteNonQuery();

            comando.CommandText = "SELECT @@IDENTITY";
            order.COD = Convert.ToInt32(comando.ExecuteScalar());
            return order.COD;

        }

        public k_order Ache(int nr_pedido) {

            OleDbCommand comando = GetCommand();

            comando.CommandText =
                "SELECT * FROM k_order WHERE NR_PEDIDO = @nr_pedido";
            comando.Parameters.Add("@nr_pedido", OleDbType.Integer).Value = nr_pedido;
            OleDbDataReader reader = comando.ExecuteReader();
            if(reader.HasRows) {
                reader.Read();
                return new k_order {
                    NR_PEDIDO = reader.GetInt32(reader.GetOrdinal("NR_PEDIDO")),
                    DateCreated = DateTime.Parse(reader.GetString(reader.GetOrdinal("DateCreated"))),
                    LastUpdated = DateTime.Parse(reader.GetString(reader.GetOrdinal("LastUpdated"))),
                    Status = reader.GetString(reader.GetOrdinal("Status"))
                };
            } else {
                return null;
            }

        }

        public void Altere(k_order order) {

            OleDbCommand comando = GetCommand();

            comando.CommandText =
                " UPDATE k_order " +
                " SET lastUpdated = @lastUpdated, status = @status " +
                " WHERE nr_pedido = @nr_pedido";
            comando.Parameters.Add("@lastUpdated", OleDbType.VarChar).Value = order.LastUpdated.ToString("s");
            comando.Parameters.Add("@status", OleDbType.VarChar).Value = order.Status;
            comando.Parameters.Add("@nr_pedido", OleDbType.Integer).Value = order.NR_PEDIDO;
            comando.ExecuteNonQuery();

        }


    }
}
